/*
 *  LEDListener.java
 * 
 *  copyright (c) 2006, tom dinchak & lorenzo orselli
 * 
 *  this file is part of jserialio.
 *
 *  jserialio is free software; you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation; either version 2 of the License, or
 *  (at your option) any later version.
 *
 *  jserialio is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *  You should have received a copy of the GNU General Public License
 *  along with jserialio; if not, write to the Free Software
 *  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
 *
 *
 *  created on July 29, 2006, 1:06 AM
 * 
 */

package serialio;

import java.io.*;
import com.illposed.osc.*;

/**
 *
 * @author tom
 */
public class LEDListener implements OSCListener {    
    Object args[];
    OutputStream serialout;
    SerialIOProcess parent = null;
    
    public LEDListener(OutputStream newserialout, SerialIOProcess parent) {
    	this.parent = parent;
        this.serialout = newserialout;
    }

    public void acceptMessage(java.util.Date time, OSCMessage message) {
        try {
            args = message.getArguments();
            System.out.println("[received] /box/led "+ args[0] + " " + args[1] + " " + args[2]);

            int msb = MonomeProtocol.LED;
            Float dataFloat = Float.parseFloat(args[2].toString());
            int data = dataFloat.intValue();
            msb += data;

            Float arg0Float = Float.parseFloat(args[0].toString());
            Float arg1Float = Float.parseFloat(args[1].toString());
            int xval = arg0Float.intValue();
            int yval = arg1Float.intValue();
            MonomeOrientation mo = new MonomeOrientation();
            int xy[] = mo.setMonomeCoord(SerialIOProcess.CableOrientation, xval, yval);
            xval = xy[0];
            yval = xy[1];
            
            
            if (xval < 0 || xval > 7 || yval < 0 || yval > 7) {
                return;
            }
            
            int lsb = (xval << 4) + (yval);
                        
            byte[] out = new byte[2];
            out[0] = (byte)msb;
            out[1] = (byte)lsb;
            serialout.write(out);
            
        } catch (Throwable t) {
        	parent.senderror = true;
        	try {
        		Thread.sleep(1000);
        	} catch (InterruptedException i) {
        		//
        	}
        	parent.senderror = false;
        	parent.rs232r.checkPorts();
        }
    }
}
